using GameFrameWork;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Pool;

/// <summary>
/// 攻击行为组件
/// </summary>
public class AttackComponent : MonoBehaviour
{
    /// <summary>
    /// 攻击策略
    /// </summary>
    public IAttackStrategy AttackStrategy { get; private set; }

    /// <summary>
    /// 攻击数据
    /// </summary>
    public SkillData AttackData { get; private set; }

    /// <summary>
    /// 自己的实体
    /// </summary>
    public Entity Own_Entity { get; private set; }

    // 优化：添加缓存相关变量
    private Entity m_CachedNearestEnemy;
    private float m_LastEnemySearchTime;
    private const float ENEMY_SEARCH_CACHE_TIME = 0.1f; // 100ms缓存

    // 对象池用于减少GC - 使用ListPool
    private static readonly List<Entity> s_TempEntityList = new List<Entity>();

    private void Awake()
    {
        Own_Entity = GetComponent<Entity>();
    }

    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="data"></param>
    public void Initialize(SkillData data)
    {
        AttackData = data;
        AttackStrategy = AttackStrategyFactory.Create(data.Type, data);
        AttackStrategy.Owner = Own_Entity;
    }

    /// <summary>
    /// 找到要攻击的敌人
    /// </summary>
    /// <returns></returns>
    public Entity FindEnemy()
    {
        // 如果实体是僵尸且有嘲讽目标，优先返回嘲讽目标
        if (Own_Entity is Zombie zombie && zombie.TauntTarget != null)
        {
            var tauntTarget = zombie.TauntTarget;
            // 检查嘲讽目标是否仍然有效
            if (tauntTarget != null && !tauntTarget.HealthComponent.IsDead)
            {
                // 检查距离是否在攻击范围内
                float distance = Vector3.Distance(Own_Entity.transform.position, tauntTarget.transform.position);
                float range = AttackData?.Range ?? float.MaxValue;
                if (distance <= range)
                {
                    return tauntTarget;
                }
            }
            else
            {
                // 如果嘲讽目标无效，清除它
                zombie.TauntTarget = null;
            }
        }
        
        // 使用服务层查找敌人
        var entityService = ServiceManager.Instance.GetService<EntityService>();
        if (entityService != null)
        {
            // 从配置服务获取缓存时间
            var configService = ServiceManager.Instance.GetService<GameConfigService>();
            float cacheTime = configService?.GetEnemySearchCacheTime() ?? ENEMY_SEARCH_CACHE_TIME;
            
            // 使用缓存减少重复计算
            if (Time.time - m_LastEnemySearchTime < cacheTime && m_CachedNearestEnemy != null)
            {
                // 验证缓存的目标是否仍然有效
                if (m_CachedNearestEnemy != null && !m_CachedNearestEnemy.HealthComponent.IsDead)
                {
                    return m_CachedNearestEnemy;
                }
            }
            
            // 使用服务层查找最近的敌人
            var nearestEnemy = entityService.FindNearestEnemy(Own_Entity, AttackData?.Range ?? float.MaxValue);
            
            // 更新缓存
            m_CachedNearestEnemy = nearestEnemy;
            m_LastEnemySearchTime = Time.time;
            return nearestEnemy;
        }
        
        // 降级方案：使用原有逻辑
        return FindEnemyFallback();
    }
    
    /// <summary>
    /// 降级查找方法
    /// </summary>
    private Entity FindEnemyFallback()
    {
        // 如果实体是僵尸且有嘲讽目标，优先返回嘲讽目标
        if (Own_Entity is Zombie zombie && zombie.TauntTarget != null)
        {
            var tauntTarget = zombie.TauntTarget;
            // 检查嘲讽目标是否仍然有效
            if (tauntTarget != null && !tauntTarget.HealthComponent.IsDead)
            {
                // 检查距离是否在攻击范围内
                float distance = Vector3.Distance(Own_Entity.transform.position, tauntTarget.transform.position);
                float range = AttackData?.Range ?? float.MaxValue;
                if (distance <= range)
                {
                    return tauntTarget;
                }
            }
            else
            {
                // 如果嘲讽目标无效，清除它
                zombie.TauntTarget = null;
            }
        }
        
        var list = FindEnemys();
        Entity entity = null;

        if (!list.IsNullOrEmpty())
        {
            // 优化：避免使用LINQ，减少GC分配
            float nearestDistance = float.MaxValue;
            Vector3 myPos = transform.position;
            
            foreach (var enemy in list)
            {
                if (enemy == null || enemy.HealthComponent.IsDead) continue;
                
                float distance = Vector3.Distance(myPos, enemy.transform.position);
                if (distance < nearestDistance)
                {
                    nearestDistance = distance;
                    entity = enemy;
                }
            }
        }

        return entity;
    }

    /// <summary>
    /// 找到全部Entity
    /// </summary>
    /// <returns></returns>
    private List<Entity> GetAllEntity()
    {
        // 使用服务层获取所有实体
        var entityService = ServiceManager.Instance.GetService<EntityService>();
        if (entityService != null)
        {
            return entityService.GetAllEntities();
        }
        
        // 降级方案：使用FindObjectsOfType + 对象池
        var allEntities = FindObjectsOfType<Entity>();
        var result = ListPool<Entity>.Get();
        result.AddRange(allEntities);
        return result;
    }


    /// <summary>
    /// 找到要攻击的敌人
    /// </summary>
    /// <returns></returns>
    public List<Entity> FindEnemys()
    {
        var list = GetAllEntity();
        if (list.IsNullOrEmpty())
        {
            return ListPool<Entity>.Get(); // 返回空List，不创建新对象
        }

        // 使用对象池减少GC分配
        s_TempEntityList.Clear();
        Vector3 myPos = transform.position;
        float rangeSquared = AttackData?.Range * AttackData.Range ?? float.MaxValue; // 使用平方距离避免开方

        foreach (var entity in list)
        {
            if (entity == null || entity.HealthComponent.IsDead) continue;
            if (entity == Own_Entity) continue;

            // 检查是否为敌人
            if (!IsEnemy(Own_Entity, entity)) continue;

            // 距离检查（使用平方距离优化）
            float distanceSquared = (entity.transform.position - myPos).sqrMagnitude;
            if (distanceSquared <= rangeSquared)
            {
                s_TempEntityList.Add(entity);
            }
        }

        // 使用对象池创建结果List
        var result = ListPool<Entity>.Get();
        result.AddRange(s_TempEntityList);
        return result;
    }

    /// <summary>
    /// 检查两个实体是否为敌人关系
    /// </summary>
    private bool IsEnemy(Entity entity1, Entity entity2)
    {
        // 土豆地雷不应该被僵尸攻击，也不应该吸引僵尸的仇恨
        if (entity1 is PotatoMine || entity2 is PotatoMine)
        {
            return false;
        }
        
        if (entity1 is Plant && entity2 is Zombie) return true;
        if (entity1 is Zombie && entity2 is Plant) return true;
        return false;
    }

    /// <summary>
    /// 临时替换攻击
    /// </summary>
    /// <param name="specialConfig"></param>
    public void ApplySpecial(SkillData specialConfig)
    {
        StartCoroutine(SpecialAttackRoutine(specialConfig));
    }

    private IEnumerator SpecialAttackRoutine(SkillData data)
    {
        var original_data = AttackData;
        AttackData = data;
        yield return new WaitForSeconds(data.Duration);
        AttackData = original_data;
    }

    private void OnDestroy()
    {
        // 清理缓存
        m_CachedNearestEnemy = null;
    }
}